using System.Security.Cryptography;
using System.Text;
using OneAuthCenter.Domain.Entities;

namespace OneAuthCenter.Infrastructure.Data;

/// <summary>
/// 数据库初始化器 - 用于创建初始数据
/// </summary>
public static class DbInitializer
{
    public static async Task InitializeAsync(AuthDbContext context)
    {
        // 确保数据库已创建
        await context.Database.EnsureCreatedAsync();

        // 检查是否已有数据
        if (context.Users.Any())
        {
            return; // 数据库已初始化
        }

        // 添加默认作用域
        var scopes = new[]
        {
            new Scope
            {
                Name = "openid",
                DisplayName = "OpenID",
                Description = "OpenID Connect 标识符",
                Required = true,
                ShowInDiscoveryDocument = true,
                IsActive = true
            },
            new Scope
            {
                Name = "profile",
                DisplayName = "用户资料",
                Description = "访问用户基本资料信息",
                Required = false,
                ShowInDiscoveryDocument = true,
                IsActive = true
            },
            new Scope
            {
                Name = "email",
                DisplayName = "电子邮件",
                Description = "访问用户电子邮件地址",
                Required = false,
                ShowInDiscoveryDocument = true,
                IsActive = true
            },
            new Scope
            {
                Name = "phone",
                DisplayName = "电话号码",
                Description = "访问用户电话号码",
                Required = false,
                ShowInDiscoveryDocument = true,
                IsActive = true
            },
            new Scope
            {
                Name = "address",
                DisplayName = "地址",
                Description = "访问用户地址信息",
                Required = false,
                ShowInDiscoveryDocument = true,
                IsActive = true
            }
        };
        context.Scopes.AddRange(scopes);

        // 添加默认管理员用户
        var adminUser = new User
        {
            Username = "admin",
            Email = "admin@oneauthcenter.com",
            PasswordHash = HashPassword("Admin@123"),
            FullName = "系统管理员",
            IsActive = true,
            Roles = "Admin,User",
            CreatedAt = DateTime.UtcNow
        };
        context.Users.Add(adminUser);

        // 添加测试用户
        var testUser = new User
        {
            Username = "testuser",
            Email = "test@oneauthcenter.com",
            PasswordHash = HashPassword("Test@123"),
            FullName = "测试用户",
            IsActive = true,
            Roles = "User",
            CreatedAt = DateTime.UtcNow
        };
        context.Users.Add(testUser);

        // 添加默认客户端
        var defaultClient = new Client
        {
            ClientId = "webapp",
            ClientSecret = GenerateClientSecret(),
            ClientName = "Web 应用程序",
            Description = "默认的 Web 应用程序客户端",
            RedirectUris = "https://localhost:5001/callback,http://localhost:5000/callback",
            PostLogoutRedirectUris = "https://localhost:5001/,http://localhost:5000/",
            AllowedGrantTypes = "authorization_code,refresh_token",
            AllowedScopes = "openid,profile,email",
            AccessTokenLifetime = 3600,
            RefreshTokenLifetime = 2592000,
            RequireConsent = true,
            RequirePkce = true,
            IsActive = true,
            CreatedAt = DateTime.UtcNow
        };
        context.Clients.Add(defaultClient);

        // 添加测试客户端（用于客户端凭证流程）
        var apiClient = new Client
        {
            ClientId = "api_client",
            ClientSecret = GenerateClientSecret(),
            ClientName = "API 客户端",
            Description = "用于服务器到服务器通信的客户端",
            RedirectUris = "",
            AllowedGrantTypes = "client_credentials",
            AllowedScopes = "api",
            AccessTokenLifetime = 3600,
            RefreshTokenLifetime = 0,
            RequireConsent = false,
            RequirePkce = false,
            IsActive = true,
            CreatedAt = DateTime.UtcNow
        };
        context.Clients.Add(apiClient);

        await context.SaveChangesAsync();
    }

    private static string HashPassword(string password)
    {
        using var sha256 = SHA256.Create();
        var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
        return Convert.ToBase64String(hashedBytes);
    }

    private static string GenerateClientSecret()
    {
        var bytes = new byte[32];
        using var rng = RandomNumberGenerator.Create();
        rng.GetBytes(bytes);
        return Convert.ToBase64String(bytes);
    }
}

